<?php

namespace app\api\controller;

use app\api\service\Token as TokenService;
use app\api\service\Order as OrderService;
use app\api\model\Order as OrderModel;
use app\api\service\UserToken;
use app\api\validate\OrderValidate;

class Order extends Common
{
    // 前置检查方法
    protected $beforeActionList = [
        'checkExclusiveScope' => ['only' => ['placeOrder']],
        'checkPrimaryScope'   => ['only' => ['detail', 'getListByUser']]
    ];

    /**
     * 订单详情
     * @param $orderId
     * @return \think\response\Json
     * @throws \app\lib\exception\ThrowError
     */
    public function detail($orderId)
    {
        (new OrderValidate('detail'))->goCheck();
        $order = OrderModel::find($orderId);
        if (!$order)
        {
            T(601002);
        }
        $order->hidden(['prepay_id']);
        return $this->response($order);
    }


    /**
     * 获取用户的订单列表
     * @param int $page
     * @param int $limit
     * @return \think\response\Json
     * @throws \app\lib\exception\ThrowError
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function getListByUser($page = 1, $limit = 15)
    {
        (new OrderValidate('getList'))->goCheck();
        $uid = UserToken::getCurrentUid();
        $list = OrderModel::getListByUser($uid, $page, $limit);
        return $this->response($list);
    }

    /**
     * 下单
     * @return \think\response\Json
     * @throws \app\lib\exception\ThrowError
     * @throws \think\Exception
     */
    public function placeOrder()
    {
        // 校验参数
        $params = (new OrderValidate('placeOrder'))->goCheck();

        // 检查用户普通权限
        $uid = TokenService::getCurrentUid();
//        $uid = 59;

        $orderProducts = json_decode($params['products'], true);
        $orderInfo = OrderService::place($uid, $orderProducts);

        return $this->response($orderInfo);

    }
}
